package com.kcloud.commons.authorization;

import com.kcloud.commons.authorization.exception.AuthorizationException;
import com.kcloud.commons.authorization.settings.biz.entity.BizFunction;
import com.kcloud.commons.authorization.settings.biz.entity.UserBizFunction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户业务功能缓存钩子，需要spring初始化时设置
 *
 * @author: songhuiqing
 */
public class AuthorizationCacheHolder {

    private static Log logger = LogFactory.getLog(AuthorizationCacheHolder.class);
    /**
     * 用户业务功能缓存，key=MD5(userId+业务功能Id), value=用户在该业务功能下的权限集合
     */
    private static Map<String, UserBizFunction> userBizFunctionCache;

    private static List<String> initDomainList = new ArrayList<>();

    /**
     * 获取用户指定业务功能的权限配置
     * @param userId 用户ID
     * @param configId 业务功能编码
     * @return
     */
    public static UserBizFunction getUserBizFunction(String userId, String configId) {
        if (userBizFunctionCache == null) {
            //权限数据未初始化
            throw new AuthorizationException("用户业务功能缓存为初始化");
        }
        return userBizFunctionCache.get(DigestUtils.md5DigestAsHex((userId + configId).getBytes()));
    }

    /**
     * 初始化用户业务功能缓存
     *
     * @param userBizFunctions 用户业务功能列表
     */
    public static void initUserBizFunctionCache(List<UserBizFunction> userBizFunctions, String domainCode) {
        if(initDomainList.contains(domainCode)) {
            return;
        }
        initDomainList.add(domainCode);
        if (userBizFunctions == null || userBizFunctions.size() == 0) {
            logger.info("用户业务功能列表为空");
            return;
        }
        if (userBizFunctionCache == null) {
            userBizFunctionCache = new HashMap<>();
        }
        userBizFunctions.forEach(ubf -> userBizFunctionCache.put(DigestUtils.md5DigestAsHex((ubf.getUserId() + ubf.getConfigId()).getBytes()), ubf));
    }

}
